<?php
require_once 'OpenId/OpenIdLogin.php';

class AccountController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    /**
     * Not really used, just for redirection
     */
    public function indexAction()
    {
        $session = new Zend_Session_Namespace("Auth");
        if (isset($session->id))
        {
            $accounts = new Application_Model_DbTable_Accounts();
            $row = $accounts->getById($session->id);
            $account = Application_Model_Account::fromTableRow($row);
            $this->_forward("config", "Account");
        }
        else
        {
            $this->_forward("login", "Account");
        }
    }

    /**
     * Register and/or login of the user
     */
    public function loginAction()
    {
        $nextAction = 'index';
        $nextController = 'Feeds';
        $request = $this->getRequest();
        $query = $request->getQuery();
        $openidLogin = new OpenIdLogin();
        if (!$openidLogin->login())
        {
            $this->_forward("error", "Account");
        }
        if (count($query) > 0)
        {
            $accounts = new Application_Model_DbTable_Accounts();
            $row = $accounts->getByEmail((string)$openidLogin->getAttribute('contact/email'));
            $account_id = 0;
            if (!$row)
            {
                $account_id = $accounts->insertAccount((string)$openidLogin,
                    (string)$openidLogin->getAttribute('contact/email'),
                    (string)$openidLogin->getAttribute('namePerson/first'),
                    (string)$openidLogin->getAttribute('namePerson/last'),
                    (string)$openidLogin->getAttribute('contact/country/home'),
                    (string)$openidLogin->getAttribute('pref/language'),
                    Application_Model_Account::DEFAULT_MAX_NEWNITS);
                $nextAction = 'config';
                $nextController = 'Account';
            }
            else
            {
                $account_id = $row['account_id'];
                $accounts->updateAccount($account_id,
                    (string)$openidLogin,
                    (string)$openidLogin->getAttribute('contact/email'),
                    (string)$openidLogin->getAttribute('namePerson/first'),
                    (string)$openidLogin->getAttribute('namePerson/last'),
                    (string)$openidLogin->getAttribute('contact/country/home'),
                    (string)$openidLogin->getAttribute('pref/language'),
                    Application_Model_Account::DEFAULT_MAX_NEWNITS);
            }
            $session = new Zend_Session_Namespace("Auth");
            $session->id = (int)$account_id;
            $this->_redirect($nextController . '/' . $nextAction);
        }
    }

    public function redirindexAction()
    {
        $this->_redirect("index");
    }

    /**
     * Settings page of the user
     */
    public function configAction()
    {
        $session = new Zend_Session_Namespace('Auth');
        if (!isset($session->id))
        {
            $this->_helper->redirector('needregister');
        }
        $request = $this->getRequest();
        $accounts = new Application_Model_DbTable_Accounts();
        $feeds_db = new Application_Model_DbTable_Feeds();
        $account_feeds_db = new Application_Model_DbTable_AccountFeeds();
        $account = Application_Model_Account::fromTableRow($accounts->getById($session->id));
        $addForm = new Application_Form_AddFeed();
        $this->view->addForm = $addForm;
        $importForm = new Application_Form_ImportOpml();
        $this->view->importForm = $importForm;
        $changeNewnitsForm = new Application_Form_ChangeMaxNewnits();
        $changeNewnitsForm->max_newnits->setValue($account->max_newnits);
        $this->view->changeNewnitsForm = $changeNewnitsForm;
        $this->view->resetAllForm = new Application_Form_ResetAll();
        if (isset($_GET['remove']))
        {
            $account_feeds_db->deleteAccountFeed($session->id, (int)$_GET['remove']);
        }
        if ($request->isPost())
        {
            if (isset($_POST['importSubmit']) && $importForm->isValid($request->getPost()))
            {
                if (!$importForm->opml->receive())
                {
                    $this->_helper->redirector('error');
                }
                $feeds = Application_Model_Feed::getFeedsFromOpml($importForm->opml->getFileName());
                $feedEntries = new Application_Model_DbTable_FeedEntries();
                $tokens = new Application_Model_DbTable_Tokens();
                $accountTokens = new Application_Model_DbTable_AccountTokens();
                foreach ($feeds as $feed)
                {
                    Application_Model_Feed::addFeed($account,
                        $accounts,
                        $feeds_db,
                        $account_feeds_db,
                        $feedEntries,
                        $tokens,
                        $accountTokens,
                        $feed);
                }
            }
            if (isset($_POST['addFeedSubmit']) && $addForm->isValid($request->getPost()))
            {
                $feed = Application_Model_Feed::fromXml($addForm->feed_url->getValue());
                if ($feed)
                {
                    $feedEntries = new Application_Model_DbTable_FeedEntries();
                    $tokens = new Application_Model_DbTable_Tokens();
                    $accountTokens = new Application_Model_DbTable_AccountTokens();
                    Application_Model_Feed::addFeed($account,
                        $accounts,
                        $feeds_db,
                        $account_feeds_db,
                        $feedEntries,
                        $tokens,
                        $accountTokens,
                        $feed);
                }
            }
            if (isset($_POST['changeMaxNewnitsSubmit']) && $changeNewnitsForm->isValid($request->getPost()))
            {
                $accounts->updateMaxNewnits($account->id, (int)$changeNewnitsForm->max_newnits->getValue());
            }
            if (isset($_POST['resetAllSubmit']) && $this->view->resetAllForm->isValid($request->getPost()))
            {
                $accountTokens = new Application_Model_DbTable_AccountTokens();
                $accountTokens->deleteByAccount($session->id);
                $accounts->updateLastUpdateTime($session->id, 0);
                $accounts->updateTokenCounts($session->id, 0, 0, 0);
            }
        }
        $this->view->feeds = $accounts->getFeedsById($session->id);
        $this->view->navbarTab = 2;
    }

    public function errorAction()
    {
        $this->render();
    }

    /**
     * Logout of the user
     */
    public function logoutAction()
    {
        $session = new Zend_Session_Namespace('Auth');
        $session->unsetAll();
        $this->_helper->redirector("index", "Index");
    }

    public function needregisterAction()
    {
        // action body
    }

    private static function tokenise($document)
    {
        $document = strtolower($document);
        preg_match_all('/\w+/', $document, $matches);
        return $matches[0];
    }
}















